var nowDate = getDay(0);
var pandianid = GetQueryString('pandianid');
var shopcode = sessionStorage.getItem("shopcode");
var userId = sessionStorage.getItem("userId");
var _config ;
$.ajax({
	type : "post",
	data:JSON.stringify({"pageUrl":location.href.replace(/\\&/g,'%26'),"corp":sessionStorage.getItem("corp")}),
	contentType: "application/json; charset=utf-8",
	async: false,
	url : "../../dingding/getconfig",
	dataType : "json",
	success : function(suc) {
		console.log(suc);
		_config = suc.config;
	}
}); 
dd.config({
	agentId : _config.agentid,
	corpId : _config.corpId,
	timeStamp : _config.timeStamp,
	nonceStr : _config.nonceStr,
	signature : _config.signature,
	jsApiList : [ 'runtime.info','biz.util.uploadImage','biz.contact.complexPicker' ]
});
function ICalendarClick(){
	
}
$(document).ready(function(){
/*	alert(sessionStorage.getItem("reload"));*/
    if(sessionStorage.getItem("reload")=='true'){
	     window.location.reload();
		sessionStorage.setItem("reload", false);
		console.log("reload"); 
	}else{
		addoperation();
		getPandianBitian();
		$('#name').text(sessionStorage.getItem("name"));
		$('#saveButton').on('click',saveInfo);
	}
	
	
});
//获取必盘项
function getPandianJianBipan(){
	var sendData = {};
	sendData.pandianid = pandianid;
	$.ajax({
		url: "../pandianevery_jd/getPandianJianBipan"
		,type:'post'
		,dataType:'json'
		,async: false
		,contentType: "application/json; charset=utf-8"
		,data:JSON.stringify(sendData) 
		,success: function(res){
			console.log(res)
			try {
				if(res.success){
					var data = res.data;
					if(data != undefined && data.length > 0){
						addPandianJianchaBipan(data);
					}
				}else{
					layer.msg(res.message);
				}
			} catch (e) {
				console.log(e)
			} finally{
				hideloading();
			}
		}
    });
}
//获取必盘项
function getPandianBitian(){
	showloading();
	var sendData = {};
	sendData.flag = 0;
	sendData.startDate = nowDate;
	sendData.endDate = nowDate;
	$.ajax({
		url: "../pandian_jd/getPandianBitian"
		,type:'post'
		,dataType:'json'
		,async: false
		,contentType: "application/json; charset=utf-8"
		,data:JSON.stringify(sendData) 
		,success: function(res){
			console.log(res)
			try {
				if(res.success){
					var data = res.data;
					$('#f_div').empty();
					if(data != undefined && data.length > 0){
						addPandianBitian(data);
						getPandianJianBipan();
					}
				}else{
					layer.msg(res.message);
				}
			} catch (e) {
				console.log(e)
			} finally{
				hideloading();
			}
		}
    });
}
function saveInfo(){
	showloading();
	try {
		var imgStr = "";
		var sendData = {};
		var insertArray = [];
		var checkFlag = true;
		$('div[itemDiv]').each(function(i,obj){
			if(checkFlag){
				var insertJson = {};
				$(obj).find('[jsonKey]').each(function(j,el){
					if($(el).parent().find('span[bitian]').text() == '*' && $(el).val() == ''){
						alert($(el).parent().find('h5').text()+"为必填项");
						checkFlag = false;
						return false;
					}else{
						var key = $(el).attr('jsonKey');
						insertJson[key] = $(el).val();
						//console.log(insertJson);
						key = null;
					}
				});
				if(checkFlag){
					//设置图片
					var img = [];
					$(obj).find('img[daibanimg]').each(function(j,el){
						img.push($(el).attr('src'));
					});
					insertJson.imgurl = img;
					//设置选项
					insertJson.optionid = $(obj).find('input[xuanxiang]:checked').attr('op');
					insertJson.optionname = $(obj).find('input[xuanxiang]:checked').val();
					insertJson.otheroptionid = $(obj).find('input[xuanxiang]:not(:checked)').attr('op');
					insertJson.otheroptionname = $(obj).find('input[xuanxiang]:not(:checked)').val();
					
				}
				if(insertJson.id == undefined){
					insertJson.pandianid = pandianid;
					insertJson.lrr = userId;
					insertJson.shopcode = shopcode;
					insertArray.push(insertJson);
				}
			}else{
				return false;
			}
		});
		console.log(sendData);
		if(checkFlag){
			sendData.dataArray = insertArray;
			$.ajax({
				url: "../pandianevery_jd/replacePandianJianBipan"
				,type:'post'
				,dataType:'json'
				,async: false
				,contentType: "application/json; charset=utf-8"
				,data:JSON.stringify(sendData) 
				,success: function(res){
					console.log(res)
					if(res.success){
						window.location.href='toJiancha_index_list?pandianid='+pandianid;
					}else{
						hideloading();
						layer.alert(res.message);
					}
				}
		    });
		}
/*		console.log(insertArray.length);*/
	} catch (e) {
		console.log(e)
	} finally{
		hideloading();
	}	
	
}	

function addPandianBitian(jsonparse){
	for(var i = 0 ;i<jsonparse.length;i++){
		var imgStr = '';
		if (jsonparse[i].isphoto == '0') {
			imgStr = '		<div class="widget-box add_mar_tb7p">'
					+'			<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'				
					+'				<h5><i class="iconfont">&#xe600;</i>&nbsp;图片上传</h5><span class="red"></span>'						  
					+'				<div class="widget-toolbar no-border" style="margin-top: 5px"  onclick="openphoto('+jsonparse[i].id+')">'
					+'					<img src="../../genius/style/mobile_page/assets/images/photo.png" />'
					+'				</div>'
					+'			</div>'				
					+'			<div class="widget-body zhediebox1">'					
					+'				<div class="widget-main pd_div" id="paizhapoUrl'+jsonparse[i].id+'" >'
					+'					<div class="clearfix"></div>'						
					+'				</div>'						
					+'			</div>'					
					+'		</div>';
		}
		var thenum = $('div[itemDiv]').length;
		$('#f_div').append('<div class="col_box" itemDiv="'+jsonparse[i].id+'">'
				+'<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_mar_tb7p">'
				+'<h5 id="wentishuomingTitle" class="black">必盘项'+(thenum+1)+'</h5>'
//				+'<div deleteIndex="'+thenum+'" class="bt_delete bg_orange">删除</div><div class="clearfix"></div>'
				+'</div>'
				+'		<div class="widget-box add_mar_tb7p">'
				+'			<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'
				+'				<h5><i class="iconfont">&#xe600;</i>&nbsp;条款</h5><span class="red" bitian></span>'
				+'				<div class="pull-right add_bor_none" style="width: 70%;margin-right: 2%; color:#474747; line-height:26px;">'+jsonparse[i].name+'</div>'
				+'			</div>'
				+'		</div>'
				+'		<div class="widget-box add_mar_tb7p">'
				+'			<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'
				+'				<h5><i class="iconfont">&#xe600;</i>&nbsp;选择</h5><span class="red" bitian></span>'
				+'				<div class="pull-right add_bor_none" style="width: 70%;margin-right: 2%; color:#474747; line-height:26px;">'
				+'					<lable style="display:block;"><input xuanxiang op="1" value="'+jsonparse[i].option1+'" type="radio" checked name="option'+jsonparse[i].id+'" style="margin-right:5px;"/><span>'+jsonparse[i].option1+'</span></lable>'
				+'					<lable style="display:block;"><input xuanxiang op="2" value="'+jsonparse[i].option2+'" type="radio" name="option'+jsonparse[i].id+'"style="margin-right:5px;"/><span>'+jsonparse[i].option2+'</span></lable>'
				+'				</div>'
				+'			</div>'
				+'		</div>'
				+'		<div class="widget-box add_mar_tb7p">'
				+'			<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'
				+'				<h5><i class="iconfont">&#xe600;</i>&nbsp;备注</h5><span class="red" bitian></span>'
				+'				<input type="text" placeholder="请输入备注" jsonKey="remark" autocomplete="off"   class="pull-right add_bor_none" style="width: 70%;margin-right: 2%"/>'
				+'			</div>'
				+'		</div>'
//				+'		<div class="widget-box add_mar_tb7p">'
//				+'			<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'
//				+'				<h5><i class="iconfont">&#xe61e;</i>&nbsp;发送到人</h5><span class="red"></span>'
//				+'				<input type="text" id="sendusername'+thenum+'" readonly="readonly" value="'+jsonparse[i].sendusername+'" onclick="openDingdingUser('+thenum+')" placeholder="请选择" jsonKey="sendusername" autocomplete="off"   class="pull-right add_bor_none" style="width: 70%;margin-right: 2%"/>'
//				+'				<input type="hidden" id="senduser'+thenum+'" value="'+jsonparse[i].senduser+'" jsonKey="senduser"/>'
//				+'			</div>'
//				+'		</div>'
				+imgStr
				+'<input type="hidden" value="'+jsonparse[i].id+'" jsonKey="itemid"/>'
				+'<input type="hidden" value="'+jsonparse[i].name+'" jsonKey="itemname"/>'
//				+'<input type="hidden" value="'+jsonparse[i].id+'" jsonKey="id"/>'
//				+'<div editIndex="'+thenum+'" class="bt_delete bg_blue">编辑</div><div class="clearfix"></div>'					
				+'</div>');
	
	}
}
function addPandianJianchaBipan(jsonparse){
	for(var i = 0 ;i<jsonparse.length;i++){
		var imgStr = '';
		var img = typeof jsonparse[i].imgurl=='string'?JSON.parse(jsonparse[i].imgurl):jsonparse[i].imgurl;
		for (var j = 0; j < img.length; j++) {
			imgStr += '<div class="wig_img">'
				+'<div class="img_box">'
				+'<img daibanimg alt="100x100" src="'+img[j]+'" onclick="showAllPic(\''+img[j]+'\')"/>'
				+'<img class="close_b" src="../../genius/style/mobile_page/assets/images/close.png" onclick="deletePhoto(this)">'
				+'</div>'
				+'</div>'
		}
		var itemIndex = jsonparse[i].itemid;
		//设置图片
		$('#paizhapoUrl'+itemIndex).empty();
		$('#paizhapoUrl'+itemIndex).append(imgStr);
		$('#paizhapoUrl'+itemIndex).append('<div class="clearfix"></div>');
		//设置input框
		$('div[itemDiv="'+itemIndex+'"]').find('input[jsonKey]').each(function(j,el){
			var key = $(el).attr('jsonKey');
			if(jsonparse[i][key] != undefined){
				$(el).val(jsonparse[i][key]);
			}
		});
		//设置单选框
		$('div[itemDiv="'+itemIndex+'"]').find('input[xuanxiang]').each(function(j,el){
			if($(el).attr('op') == jsonparse[i].optionid){
				$(el).attr('checked','checked');
			}
		});
	}	
}


function addoperation(){
//	$('#addButton').append(
//		'<div class="submit_button w94 bg_red">'
//	   +'<span  style="display:inline-block; width:16px; height:16px!important; line-height:14px!important; font-weight:600; font-size:15px; text-align:center; border:1px #fff solid; border-radius:10px; color:#fff!important;">+</span>'
//  	   +'新增问题反馈</div>'
//	);
	
	 $('#saveButton').append('<div class="submit_button w94">提交</div>');
}

//打开钉钉拍照
function openphoto(index){
	
	dd.ready(function(){
		dd.biz.util.uploadImage({
		    compression: false,//(是否压缩，默认为true)
		    quality: 100, // 图片压缩质量, 
		    resize: 100, // 图片缩放率
		    stickers: {   // 水印信息
		        time: nowDate,
		        username: sessionStorage.getItem("name")
		    },
		    onSuccess : function(result) {
				$('#paizhapoUrl'+index+' .clearfix').remove()
				$('#paizhapoUrl'+index).append('<div class="wig_img">'
						+'<div class="img_box">'
						+'<img daibanimg alt="100x100" src="'+result[0]+'" onclick="showAllPic(\''+result[0]+'\')"/>'
						+'<img class="close_b" src="../../genius/style/mobile_page/assets/images/close.png" onclick="deletePhoto(this)">'
						+'</div>'
						+'</div>');
				$('#paizhapoUrl'+index).append('<div class="clearfix"></div>');
		    },
		    onFail : function(err) {}
		});
	});
	dd.error(function(err) {
		alert(JSON.stringify(err));
		
//		alert('dd error: ' + JSON.stringify(err));
	});
}	
//删除图片
function deletePhoto(obj){
	dd.device.notification.confirm({
	    message: "删除图片吗",
	    title: "提示",
	    buttonLabels: ['是', '否'],
	    onSuccess : function(result) {
	    	if(result.buttonIndex == '0'){
	    		var index = $(obj).parent().parent().index();
	    		$(obj).parent().parent().remove();
	    		photoUrl.splice(index,1);
	    	}
	        
	    },
	    onFail : function(err) {}
	});
	 
}
//预览图片
function showAllPic(imgOne){
	dd.biz.util.previewImage({
		urls: imgOne.split(','),//图片地址列表
		current: imgOne,//当前显示的图片链接
		onSuccess : function(result) {
			/**/
		},
		onFail : function(err) {}
	})
}
